package com.lightkits.wms.domain.purchasereceive;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.TransactionValidate;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.ScmPoLine;
import com.lightkits.common.db.entity.SysFile;
import com.lightkits.common.db.entity.WmDeliveryTicketLine;
import com.lightkits.common.db.entity.WmDeliveryTicketLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.json.JsonUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.common.pipeline.session.SessionInfo;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsScmPoLineMapper;
import com.lightkits.wms.database.model.PoReceivedHistoryModel;
import com.lightkits.wms.domain.stocktransfer.service.impl.SubStockTransferDomainImpl;
import com.lightkits.wms.dto.purchasereceive.GetPoHistoryResponseType;
import com.lightkits.wms.dto.purchasereceive.GetPoHistoryRequestType;
import com.lightkits.wms.dto.purchasereceive.models.PoHistoryDTO;
import com.lightkits.wms.util.models.LineControl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购订单历史详情
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/27 16:14
 */
@Component
public class PoHistoryExecutor implements ServiceExecutor<GetPoHistoryRequestType, GetPoHistoryResponseType> {
    private final WmsScmPoLineMapper scmPoLineMapper;
    private static final Logger LOGGER = LoggerFactory.getLogger(SubStockTransferDomainImpl.class);

    @Autowired
    public PoHistoryExecutor(WmsScmPoLineMapper scmPoLineMapper) {
        this.scmPoLineMapper = scmPoLineMapper;
    }

    @Override
    public GetPoHistoryResponseType service(GetPoHistoryRequestType request) {
        GetPoHistoryResponseType response = new GetPoHistoryResponseType();
        response.setSuccessful(true);
        try {
            IntegrityValidator.begin()
                    .validate(request.getPoLineId(), "PO Line Id")
                    .validate(request.getTicketLineId(), "Ticket Line Id");
            TransactionValidate check = TransactionValidate.beginValidity(ScmPoLine.class);
            check.checkIdValidity(ObjectUtil.toString(request.getPoLineId()), "ID");

            check = TransactionValidate.beginValidity(WmDeliveryTicketLine.class);
            check.checkIdValidity(ObjectUtil.toString(request.getTicketLineId()), "ID");

            PoReceivedHistoryModel model = scmPoLineMapper.getCompletedByParams(request.getPoLineId(),
                    request.getTicketLineId(), SessionInfo.languageCode());
            if (model == null) {
                response.setDto(new PoHistoryDTO());
                return response;
            }
            response.setDto(convertDTO(model));

        } catch (LightKitsBizException e) {
            response.setSuccessful(false);
            String mes = StringUtils.substringAfterLast(e.getMessage(), ":");
            response.setMessage(ObjectUtil.isNullOrEmpty(mes) ? e.getMessage() : mes);
        } catch (Exception e) {
            e.printStackTrace();
            response.setSuccessful(false);
            response.setMessage("get Purchase List Error");
        }
        return response;
    }

    private PoHistoryDTO convertDTO(PoReceivedHistoryModel model) {
        PoHistoryDTO dto = new PoHistoryDTO();
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");

        try {
            dto.setTciketNum(model.getTciketNum());
            dto.setActualDate(df.format(model.getActualDate()));
            dto.setDemandDate(df.format(model.getDemandDate()));
            dto.setItemCode(model.getItemCode());
            dto.setItemDesc(model.getItemDesc());
            //根据单位中deciamal_number字段的保留小数位
            FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                    .eq(FndUomBase.UOM_CODE, model.getUomName()));
            if (ObjectUtil.isEmpty(uomBase)) {
                dto.setDemandQty(model.getDemandQty().toString());
                dto.setReceiveQty(model.getReceiveQty().toString());
            } else {
                dto.setReceiveQty(model.getReceiveQty()
                        .setScale(uomBase.getDecimalNumber().intValue()
                                , BigDecimal.ROUND_HALF_UP).toString());
                dto.setDemandQty(model.getDemandQty()
                        .setScale(uomBase.getDecimalNumber().intValue()
                                , BigDecimal.ROUND_HALF_UP).toString());
            }
            //根据pictureId查询图片的Url
            if (!ObjectUtil.isNullOrEmpty(model.getPictureId())) {
                LineControl lineControl = JsonUtil.parse(model.getPictureId(), LineControl.class);
                List<String> pictureIds = lineControl.getPictureIds();
                List<String> pictureUrls = new ArrayList<>();
                pictureIds.forEach(target -> {
                    SysFile sysFile = new SysFile().selectById(target);
                    if (sysFile != null) {
                        pictureUrls.add(sysFile.getFileUrl());
                    }
                });
                dto.setPictureUrls(pictureUrls);
            }
            dto.setOrgName(model.getOrgName());
            dto.setReceiveNum(model.getReceiveNum());
            dto.setReceiverName(model.getReceiverName());
            dto.setRemark(model.getRemark());
            dto.setWarehouseName(model.getWarehouseName());
            dto.setUomName(model.getUomName());
            dto.setSupplierSite(model.getSupplierSite());
            dto.setSupplierNum(model.getSupplierNum());
            dto.setContact(model.getContact());
            dto.setSupplierName(model.getSupplierName());
            dto.setLotCode(model.getLotCode());
        } catch (Exception e) {
            LOGGER.error("convertDTO.error", e);
            throw new LightKitsBizException(e);
        }
        return dto;
    }
}
